﻿using B.S.BasicData.Domain;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure;
using B.S.BasicData.Infrastructure.Interfance;
using B.S.BasicData.Read.Apilication.Common.Exec;
using B.S.BasicData.Read.DTOS;
using MediatR;

namespace B.S.BasicData.Read.Apilication.Handler.Exec
{
    public class GetleavesummaryCommandHandle:IRequestHandler<GetleavesummaryCommand,ApiResult<List<ReportDto>>>
    {
        private readonly SCDbContext dbContext;
        private readonly IBaseRepository<UserModel> UserDal;
        private readonly IBaseRepository<LeaveModel> LeaveDal;
        public GetleavesummaryCommandHandle(SCDbContext dbContext, IBaseRepository<UserModel> userDal, IBaseRepository<LeaveModel> leaveDal)
        {
            this.dbContext = dbContext;
            UserDal = userDal;
            LeaveDal = leaveDal;
        }

        public Task<ApiResult<List<ReportDto>>> Handle(GetleavesummaryCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<ReportDto>> res = new ApiResult<List<ReportDto>>();
            //获取所有用户
            var users = dbContext.UserModel.ToList();

            //初始化汇总数据
            var summarylist = new List<ReportDto>();

            foreach (var user in users)
            {
                var summary = new ReportDto
                {
                    UserId = user.UserId,
                    UserName = user.UserName,
                    MonthlyHours = new List<int>(new int[12])
                };

                //查询用户在指定年份的所有请假记录
                var leaveRecords = LeaveDal.GetAll().Where(x => x.UserId == user.UserId && x.leaveTime.Year == request.Year).ToList(); ;

                //统计每个月的请假工时
                foreach (var item in leaveRecords)
                {
                    int month = item.leaveTime.Month - 1;
                    summary.MonthlyHours[month] += item.Number;
                }
                summarylist.Add(summary);


            }
            res.Data = summarylist;
            res.Code = ApiEnum.Success;
            res.Message = "查询成功";
            return Task.FromResult(res);
        }


    }
}
